package main

import (
	"bufio"
	"encoding/json"
	"go.uber.org/zap"
	"net"
	"strings"
)

var clientList = make(map[string]interface{})
var getClientModel GetClientModel

func InitServer() {
	//wg.Add(1)
	listen, err := net.Listen("tcp", "0.0.0.0:8089")
	if err != nil {
		logger.Error("连接错误", zap.Error(err))
		logger.Error(
			"连接错误：",
			zap.Error(err),
		)
	} else {
		logger.Warn("连接成功：0.0.0.0:8089")
	}
	for {
		conn, err := listen.Accept()
		if err != nil {
			logger.Error("监听端口错误：", zap.Error(err))
		}
		go process(conn)
	}
	//wg.Done()
}

func process(conn net.Conn) {
	defer conn.Close()
	for {
		reader := bufio.NewReader(conn)
		var buf = make([]byte, 4096)
		n, err := reader.Read(buf)
		if err != nil {
			logger.Error("从客户端读取数据错误：", zap.Error(err))
			clientIp := conn.RemoteAddr()
			res := strings.Split(clientIp.String(), ":")
			getClientModel.ClientStatus = false
			clientList[res[0]] = getClientModel
			break
		} else {
			//conString := string(buf[:n])
			json.Unmarshal(buf[:n], &getClientModel)
			clientIp := conn.RemoteAddr()
			logger.Info("client：", zap.String(clientIp.String(), string(buf[:n])))
			res := strings.Split(clientIp.String(), ":")
			getClientModel.ClientStatus = true
			clientList[res[0]] = getClientModel
		}
	}
}
